#include <Arduino.h>
#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifim;
#elif ESP32
#include <WiFi.h>
#include <WiFiMulti.h>
WiFiMulti wifim;
#endif
#include "eeprom_.h"
#define ap_ssid "esp_ap"
#define ap_pass "88888888"
extern int wifi_mode_is_ap;
extern int blinker_enable;
void wifi_conn_setup()
{

    // 尝试sta连接wifi
    IPAddress ip;      // 想要设定的静态ip
    IPAddress gateway; // 当前网关
    IPAddress subnet;  // 当前子网掩码
    IPAddress dns;     // DNS
    String ssid = eeprom_get_string(SSID_INDEX);
    String pass = eeprom_get_string(PASS_INDEX);
    ip.fromString(eeprom_get_string(IP_INDEX));
    gateway.fromString(eeprom_get_string(GATEWAY_INDEX));
    subnet.fromString(eeprom_get_string(SUBNET_INDEX));
    dns.fromString(eeprom_get_string(DNS_INDEX));
    // blinker和静态ip冲突
    // if (!blinker_enable)
    // {
    WiFi.config(ip, gateway, subnet, dns); // 设置静态IP
    //}

    WiFi.mode(WIFI_STA);
    Serial.print("\nconnect ");
    Serial.print(ssid);
    Serial.print("  ");
    Serial.println(pass);
    wifim.addAP(ssid.c_str(), pass.c_str());
    for (int i = 0; i < 3; i++)
    {
        if (wifim.run() == WL_CONNECTED)
        // if (WiFi.begin(ssid.c_str(), pass.c_str())== WL_CONNECTED)
        {
            Serial.println("\nweb address http://" + WiFi.localIP().toString());
            wifi_mode_is_ap = false;
            WiFi.setAutoConnect(true);
            WiFi.setAutoReconnect(true);
            break;
        }
        Serial.print(".");
        delay(500);
    }
    // sta连接失败则进入AP模式
    if (wifi_mode_is_ap)
    {
        Serial.println("\nap模式");
        IPAddress ip_ap(192, 168, 1, 123);
        IPAddress gateway_ap(192, 168, 1, 123);
        IPAddress subnet_ap(255, 255, 255, 0);
        WiFi.mode(WIFI_AP);

        WiFi.softAPConfig(ip_ap, gateway_ap, subnet_ap);
        while (!WiFi.softAP(ap_ssid, ap_pass))
        {
            delay(100);
        };
    }
}